﻿// 文件使用MiniExcel源码， 使用时需遵循其 Apache License 2.0
// 修改摘要通知： 删除异步、Task等net2.0中不支持的内容，替换原先C#自带的zip处理方式，改用yacomp 进行解压缩。
using ExcelConfig.helpers;
using ExcelConfig.Utils;
using ExcelConfig.Zip;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using yacomp.os;

namespace ExcelConfig.OpenXml.SaveByTemplate
{
    internal partial class ExcelOpenXmlTemplate
    {
        public void MergeSameCells(string path)
        {
            using (var stream = FileHelper.OpenSharedRead(path))
                MergeSameCellsImpl(stream);
        }

        public void MergeSameCells(byte[] fileInBytes)
        {
            using (Stream stream = new MemoryStream(fileInBytes))
                MergeSameCellsImpl(stream);
        }

        private void MergeSameCellsImpl(Stream stream)
        {
            helper.ReadAllToMemory(stream, _outputFileStream);

            var reader = new ExcelOpenXmlSheetReader(_outputFileStream, null);
            var archive = new ExcelOpenXmlZip(_outputFileStream, true, Encoding.UTF8);

            //read sharedString
            var sharedStrings = reader._sharedStrings;

            //read all xlsx sheets
            var sheets = new List<YacompFile>();
            foreach (var entry in archive.zipFile.storage.LoopFiles())
                if (entry.FullPath.StartsWith("xl/worksheets/sheet", StringComparison.OrdinalIgnoreCase) ||
                entry.FullPath.StartsWith("/xl/worksheets/sheet", StringComparison.OrdinalIgnoreCase))
                    sheets.Add(entry);

            foreach (var sheet in sheets)
            {
                _xRowInfos = new List<XRowInfo>(); //every time need to use new XRowInfos or it'll cause duplicate problem: https://user-images.githubusercontent.com/12729184/115003101-0fcab700-9ed8-11eb-9151-ca4d7b86d59e.png
                _xMergeCellInfos = new Dictionary<string, XMergeCell>();
                _newXMergeCellInfos = new List<XMergeCell>();

                var sheetStream = sheet.ToStream();
                var fullName = sheet.FullPath;

                var entry = archive.CreateEntry(fullName);
                using (var zipStream = entry.ToStream())
                {
                    GenerateSheetXmlImplByUpdateMode(sheet, zipStream, sheetStream, new Dictionary<string, object>(), sharedStrings, mergeCells: true);
                    //doc.Save(zipStream); //don't do it beacause: https://user-images.githubusercontent.com/12729184/114361127-61a5d100-9ba8-11eb-9bb9-34f076ee28a2.png
                }
            }

            archive.zipFile.Dispose();
        }
    }
}